using QRCoder;
using Microsoft.AspNetCore.Http;

namespace Unified.payment.code.Services
{
    public class UnifiedPaymentService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public UnifiedPaymentService(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 生成统一支付二维码（包含微信和支付宝支付链接）
        /// </summary>
        /// <param name="wechatPayUrl">微信支付链接</param>
        /// <param name="alipayUrl">支付宝支付链接</param>
        /// <returns>Base64编码的二维码图片</returns>
        public string GenerateUnifiedPaymentQrCode(string wechatPayUrl, string alipayUrl)
        {
            // 获取当前请求的BaseUrl
            var request = _httpContextAccessor.HttpContext.Request;
            var baseUrl = $"{request.Scheme}://{request.Host}";
            
            // 创建包含两个支付链接的统一链接
            // 这里使用URL编码来确保链接正确
            var unifiedUrl = $"{baseUrl}/SmartPay?wechat={Uri.EscapeDataString(wechatPayUrl)}&alipay={Uri.EscapeDataString(alipayUrl)}";

            // 使用QRCoder生成二维码
            using (var qrGenerator = new QRCodeGenerator())
            {
                var qrCodeData = qrGenerator.CreateQrCode(unifiedUrl, QRCodeGenerator.ECCLevel.Q);
                using (var qrCode = new PngByteQRCode(qrCodeData))
                {
                    var qrCodeImage = qrCode.GetGraphic(20);
                    return Convert.ToBase64String(qrCodeImage);
                }
            }
        }

        /// <summary>
        /// 生成一个智能识别二维码，根据用户设备类型自动选择支付方式
        /// </summary>
        /// <param name="wechatPayUrl">微信支付链接</param>
        /// <param name="alipayUrl">支付宝支付链接</param>
        /// <returns>Base64编码的二维码图片</returns>
        public string GenerateSmartPaymentQrCode(string wechatPayUrl, string alipayUrl)
        {
            // 获取当前请求的BaseUrl
            var request = _httpContextAccessor.HttpContext.Request;
            var baseUrl = $"{request.Scheme}://{request.Host}";
            
            // 创建一个中间页面URL，该页面会根据用户代理自动跳转到相应的支付方式
            var smartUrl = $"{baseUrl}/SmartPay?wechat={Uri.EscapeDataString(wechatPayUrl)}&alipay={Uri.EscapeDataString(alipayUrl)}";

            // 使用QRCoder生成二维码
            using (var qrGenerator = new QRCodeGenerator())
            {
                var qrCodeData = qrGenerator.CreateQrCode(smartUrl, QRCodeGenerator.ECCLevel.Q);
                using (var qrCode = new PngByteQRCode(qrCodeData))
                {
                    var qrCodeImage = qrCode.GetGraphic(20);
                    return Convert.ToBase64String(qrCodeImage);
                }
            }
        }
    }
}